﻿using CommunityToolkit.Mvvm.ComponentModel;
using LongSCADA_WPF.Helpers;
using LongSCADA_WPF.Models;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LongSCADA_WPF.ViewModels
{
    public partial class IndexViewModel:ObservableObject
    {
        private readonly GlobalHelper _globalHelper;
        private readonly RootParam _rootParam;
        private CancellationTokenSource _cts = new();

        [ObservableProperty]
        ScadaReadData _scadaReadDataProp = new();
        public IndexViewModel(GlobalHelper globalHelper,IOptionsSnapshot<RootParam> options)
        {
            _globalHelper = globalHelper;
            _rootParam = options.Value;
            StartCollectionIndex();

            InitReadDataAndScadaData();
        }

        /// <summary>
        /// 采集数据
        /// </summary>
        private async Task StartCollectionIndex()
        {
            await _globalHelper.InitPlcConnectionAsync();
            if (_rootParam.PlcParam.AutoCollect)
            {
                await _globalHelper.StartReadDataAsync();
            }
        }

        /// <summary>
        /// 将PLC数据与 IndexView 界面绑定
        /// </summary>
        private void InitReadDataAndScadaData()
        {
            Task.Run(async() =>
            {
                //通过反射拿到所有的属性
                var propertis = typeof(ScadaReadData)
                .GetProperties()
                .Where(p=>p.PropertyType==typeof(bool)||p.PropertyType==typeof(float));

                while(!_cts.Token.IsCancellationRequested){
                    foreach (var property in propertis)
                    {
                        try
                        {
                            if (property.PropertyType == typeof(bool))
                            {
                                bool value = _globalHelper.GetValue<bool>(property.Name);
                                property.SetValue(ScadaReadDataProp, value);
                            }
                            else if (property.PropertyType == typeof(float))
                            {
                                float value = _globalHelper.GetValue<float>(property.Name);
                                property.SetValue(ScadaReadDataProp, value);
                            }
                        }
                        catch (Exception e)
                        {

                            Debug.WriteLine(e.Message);
                        }
                    }
                    await Task.Delay(100);
                }
            });
        }
    }
}
